﻿using System.Data.SqlClient;
using GeneralLibs;
using System.Collections;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using DevExpress.XtraPrinting;
using DevExpress.Utils;
using DevExpress.XtraGrid;

namespace MuaHang.CongCuDatHang
{
    public partial class FrmCongCuDatHang : BasicForms.FrmClose
    {
        public FrmCongCuDatHang()
        {
            InitializeComponent();
        }

        StyleFormatCondition _StyleConditionGioiHanSoNgayConHang = new DevExpress.XtraGrid.StyleFormatCondition();
        private bool _ActionBYLoad = false;

        public void RequestCreateNewPhieuDatHang(DataTable dt, Guid doiTuongNghiepVu)
        {
            try
            {
                FrmDanhSachPhieuDatHang frm = new FrmDanhSachPhieuDatHang();
                frm.CreateNewRef(dt, doiTuongNghiepVu);
            }
            catch (SqlException sqlEx)
            {
                throw new CustomException(CustomException.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                if (ex is CustomException) throw ex;
                else
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        private void FrmCongCuDatHang_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            cmbNhaCungCap.PopupWidth = 500;
            cmbNhaCungCap.PopupHeight = 200;
            try
            {
                cmbKho.DataSource = DanhMucKho.Instance.DataView;
                cmbKho.DisplayColumn = "Ten";
                cmbKho.ValueColumn = "ID";
                cmbKho.AddVisibleColumn("Ma", "Mã");
                cmbKho.AddVisibleColumn("Ten", "Tên");
                cmbKho.EditValue = Guid.Empty;

                cmbNhaCungCap.DataSource = DanhMucDoiTuongNghiepVu.GetDanhMucNhaCungCap().DataView;
                cmbNhaCungCap.DisplayColumn = "Ten";
                cmbNhaCungCap.ValueColumn = "ID";
                cmbNhaCungCap.AddVisibleColumn("Ma", "Mã", 40);
                cmbNhaCungCap.AddVisibleColumn("Ten", "Tên", 300);

                //cmbKyBaoCao.SelectedIndex = 17;
                cmbKyBaoCao.Text = "Tùy chọn";
                txtGioiHanSoLuongTon.EditValue = 1000000000;
                nmrGioiHanNgay.Text = "10";

                cmbNhaCungCap.EditValue = Guid.Empty;
                dsCongCuDatHang.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangHoaDangSuDungCoCotChoose());
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }

            _ActionBYLoad = true;
            //chkChooseAllVatTuHangHoa.Checked = false;
            colTacGia.Visible = false;
            colNXB.Visible = false;
            colNCC.Visible = false;

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsVatTuHangHoa.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewShow.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            //foreach (DataRow row in dsCongCuDatHang.VatTuHangHoa.Rows)
            //{
            //    row["Choose"] = true;
            //}

            StyleFormatCondition styleConditionGioiHanTon = new DevExpress.XtraGrid.StyleFormatCondition();
            styleConditionGioiHanTon.Appearance.BackColor = Color.Red;
            styleConditionGioiHanTon.Appearance.Options.UseBackColor = true;
            styleConditionGioiHanTon.Column = gridViewShow.Columns["SoLuongTra"];
            styleConditionGioiHanTon.Condition = FormatConditionEnum.Between;
            styleConditionGioiHanTon.Value1 = 0;
            styleConditionGioiHanTon.Value2 = 1000000;
            styleConditionGioiHanTon.ApplyToRow = true;
            gridViewShow.FormatConditions.Add(styleConditionGioiHanTon);

            _StyleConditionGioiHanSoNgayConHang.Appearance.BackColor = Color.LawnGreen;
            _StyleConditionGioiHanSoNgayConHang.Appearance.Options.UseBackColor = true;
            _StyleConditionGioiHanSoNgayConHang.Column = gridViewShow.Columns["DuDoanSoNgayConHang"];
            _StyleConditionGioiHanSoNgayConHang.Condition = FormatConditionEnum.Between;
            _StyleConditionGioiHanSoNgayConHang.Value1 = 0;
            _StyleConditionGioiHanSoNgayConHang.Value2 = Convert.ToInt32(nmrGioiHanNgay.Text);
            _StyleConditionGioiHanSoNgayConHang.ApplyToRow = true;
            gridViewShow.FormatConditions.Add(_StyleConditionGioiHanSoNgayConHang);

            FormatTextEdit(txtGioiHanSoLuongTon, TextFormatType.Money);
            gridControlDsVatTuHangHoa.DataSource = dsCongCuDatHang.VatTuHangHoa;
            FormatNumberInGridView(gridViewDsVatTuHangHoa);
            colMa1.SortOrder = DevExpress.Data.ColumnSortOrder.None;
        }

        private void chkChooseAllVatTuHangHoa_CheckedChanged(object sender, EventArgs e)
        {
            FrmProgressBarDev.StartShowProgress();
            foreach (DataRow row in dsCongCuDatHang.VatTuHangHoa.Rows)
            {
                row["Choose"] = chkChooseAllVatTuHangHoa.Checked;
            }
            FrmProgressBarDev.FinishShowProgress();
        }

        private void cmbNhaCungCap_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbNhaCungCap.EditValue = Guid.Empty;
        }
        private void cmbNhaCungCap_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmbNhaCungCap.EditValue is Guid && (Guid)cmbNhaCungCap.EditValue != Guid.Empty)
                {
                    dsCongCuDatHang.VatTuHangHoa.Clear();
                    if (cmbNhaCungCap.EditValue is Guid && (Guid)cmbNhaCungCap.EditValue != Guid.Empty)
                        dsCongCuDatHang.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangMuaTuNhaCungCap_TruHangKhongDung((Guid)cmbNhaCungCap.EditValue));
                    else
                        dsCongCuDatHang.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangHoaDangSuDung().DataView.ToTable());
                }
                else
                {
                    dsCongCuDatHang.VatTuHangHoa.Clear();
                }
                chkChooseAllVatTuHangHoa.Checked = false;
                chkChooseAllVatTuHangHoa.Checked = true;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
            }
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = new DateTime(); if (LocalSettings.HeThong.CheDoBiKiemTra) ngayBatDau = DateTime.Now.AddDays(-2); else ngayBatDau = dtNgayBatDau.DateTime; //DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if (!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;

            int gioiHanSoLuong = 1000000000;
            if (txtGioiHanSoLuongTon.EditValue is int)
                gioiHanSoLuong = (int)txtGioiHanSoLuongTon.EditValue;

            Guid khoID = Guid.Empty;
            if (cmbKho.EditValue is Guid && (Guid)cmbKho.EditValue != Guid.Empty)
                khoID = (Guid)cmbKho.EditValue;

            if (!(cmbNhaCungCap.EditValue is Guid) && (Guid)cmbNhaCungCap.EditValue == Guid.Empty)
            {
                MessageBox.Show("Phải chọn nhà cung cấp");
            }

            BasicForms.FrmProgressBarDev.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                dsCongCuDatHang.Detail.Clear();

                int count = 0;
                int total = dsCongCuDatHang.VatTuHangHoa.Select("Choose = 1").Length;

                foreach (DataRow row in dsCongCuDatHang.VatTuHangHoa.Rows)
                {
                    if (row["Choose"] is bool && (bool)row["Choose"])
                    {
                        BasicForms.FrmProgressBarDev.Status = string.Format("Đang xử lý {0}/{1}", count, total);
                        count++;

                        Guid vatTuHangHoaID = (Guid)row["ID"];
                        VatTuHangHoa vatTuHangHoa = DanhMucVatTuHangHoa.Instance.GetByID(vatTuHangHoaID);
                        ThoiDiemKhoaSo thoiDiemKhoaSoGanNhat = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemChotSoDuGanNhat(ngayBatDau);

                        TonKho tonDauKy = TonKho.CalculateTongTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVao(cmd, thoiDiemKhoaSoGanNhat.ThoiDiem.AddSeconds(2), vatTuHangHoaID);
                        TonKho tonKho = new TonKho();
                        TonKho xuatTra = new TonKho();
                        TonKho phatSinhNhap = new TonKho();
                        TonKho phatSinhXuat = new TonKho();
                        decimal soLuongBanTBTheoThang = 0, duDoanSoNgayConHang = 0, soLuongBanTBTheoNgay = 0;

                        if (khoID == Guid.Empty)
                        {
                            tonKho = TonKho.CalculateTongTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVao(ngayKetThuc, vatTuHangHoaID);
                            xuatTra = TonKho.CalculatePhatSinhXuatTraMatHang(cmd, ngayBatDau, ngayKetThuc, (Guid)cmbNhaCungCap.EditValue, vatTuHangHoaID);
                            phatSinhNhap = TonKho.CalculatePhatSinhNhapToanBo(cmd, ngayBatDau, ngayKetThuc, vatTuHangHoaID);
                            phatSinhXuat = TonKho.CalculatePhatSinhXuatToanBo(cmd, ngayBatDau, ngayKetThuc, vatTuHangHoaID);
                            soLuongBanTBTheoThang = DanhMucVatTuHangHoa.SoLuongBanRaTrungBinh(cmd, vatTuHangHoaID, false);//Theo tháng
                            soLuongBanTBTheoNgay = DanhMucVatTuHangHoa.SoLuongBanRaTrungBinh(cmd, vatTuHangHoaID, true);//Theo ngày
                            if (soLuongBanTBTheoNgay != 0 && tonKho != null && tonKho.SoLuong > 0)
                                duDoanSoNgayConHang = tonKho.SoLuong / soLuongBanTBTheoNgay;
                        }
                        else
                        {
                            tonKho = TonKho.CalculateTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVaoTheoKho(cmd, ngayKetThuc, khoID, vatTuHangHoaID);
                            xuatTra = TonKho.CalculatePhatSinhXuatTraMatHangTheoKho(cmd, ngayBatDau, ngayKetThuc, khoID, (Guid)cmbNhaCungCap.EditValue, vatTuHangHoaID);
                            phatSinhNhap = TonKho.CalculatePhatSinhNhap(cmd, ngayBatDau, ngayKetThuc, khoID, vatTuHangHoaID);
                            phatSinhXuat = TonKho.CalculatePhatSinhXuat(cmd, ngayBatDau, ngayKetThuc, khoID, vatTuHangHoaID);
                            soLuongBanTBTheoThang = DanhMucVatTuHangHoa.SoLuongBanRaTrungBinh(cmd, vatTuHangHoaID, false);//Theo tháng
                            soLuongBanTBTheoNgay = DanhMucVatTuHangHoa.SoLuongBanRaTrungBinh(cmd, vatTuHangHoaID, true);//Theo ngày
                            if (soLuongBanTBTheoNgay != 0 && tonKho != null && tonKho.SoLuong > 0)
                                duDoanSoNgayConHang = tonKho.SoLuong / soLuongBanTBTheoNgay;
                        }

                        if (tonKho.SoLuong < gioiHanSoLuong && vatTuHangHoa != null)
                        {
                            DataRow addedRow = dsCongCuDatHang.Detail.NewRow();

                            addedRow["Ma"] = vatTuHangHoa.Ma;
                            addedRow["Ten"] = vatTuHangHoa.Ten;
                            addedRow["GiaBia"] = vatTuHangHoa.GiaBia;
                            addedRow["SoLuongDat"] = 0;
                            addedRow["TenNhomVatTuHangHoa"] = DanhMucNhomVatTuHangHoa.Instance.GetByID(vatTuHangHoa.NhomVatTuHangHoa.ID).Ten;
                            addedRow["SoLuongTonDauKy"] = tonDauKy.SoLuong;
                            addedRow["SoLuongNhap"] = phatSinhNhap.SoLuong;
                            addedRow["SoLuongXuat"] = phatSinhXuat.SoLuong - xuatTra.SoLuong;
                            addedRow["SoLuongTon"] = tonKho.SoLuong;
                            addedRow["LuongBanTrungBinhTheoThang"] = soLuongBanTBTheoThang;
                            addedRow["DuDoanSoNgayConHang"] = duDoanSoNgayConHang;
                            addedRow["SoLuongTra"] = xuatTra.SoLuong;
                            addedRow["NguonCungCap"] = vatTuHangHoa.NguonCungCap;

                            //#region Tinh tôn riêng của nhà này
                            //decimal soLuongTonRieng = 0;
                            ////decimal thanhTienTonRieng = 0;
                            ////decimal donGiaTonRieng = 0;
                            //Hashtable htTonRieng = TonKho.CalculateTonTheoNhaCungCapFromDB(cmd, ngayKetThuc, vatTuHangHoaID);
                            //if (htTonRieng.ContainsKey((Guid)cmbNhaCungCap.EditValue))
                            //{
                            //    TonKho tonRieng = htTonRieng[(Guid)cmbNhaCungCap.EditValue] as TonKho;
                            //    soLuongTonRieng += tonRieng.SoLuong;
                            //    //thanhTienTonRieng += tonRieng.ThanhTien;
                            //}
                            ////if (soLuongTonRieng > 0) donGiaTonRieng = thanhTienTonRieng / soLuongTonRieng;
                            //addedRow["TongTonTheoNhaCungCap"] = soLuongTonRieng;
                            ////addedRow["DonGiaTonRieng"] = donGiaTonRieng;
                            ////addedRow["ThanhTienTonRieng"] = thanhTienTonRieng;
                            //#endregion

                            dsCongCuDatHang.Detail.Rows.Add(addedRow);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }

            gridControlShow.DataSource = AlphabeticSort(dsCongCuDatHang.Detail, "TenNhomVatTuHangHoa", 0).DefaultView; //Sort theo nhom hang
            FormatNumberInGridView(gridViewShow);
            FormatNumberInGridView(gridViewDsVatTuHangHoa);

            BasicForms.FrmProgressBarDev.FinishShowProgress();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            printableComponentLink1.Component = gridControlShow;
            printableComponentLink1.PaperKind = System.Drawing.Printing.PaperKind.A4;
            //printableComponentLink1.CreateReportHeaderArea +=  new CreateAreaEventHandler(printableComponentLink1_CreateReportHeaderArea);
            printableComponentLink1.ShowPreview();
            //gridControlShow.ShowPrintPreview();
        }
        private void printableComponentLink1_CreateReportHeaderArea(object sender, CreateAreaEventArgs e)
        {
            string reportHeader = "Dat hang";
            e.Graph.StringFormat = new BrickStringFormat(StringAlignment.Near);
            e.Graph.Font = new Font("Tahoma", 14, FontStyle.Bold);
            RectangleF rec = new RectangleF(0, 0, e.Graph.ClientPageSize.Width, 50);
            e.Graph.DrawString(reportHeader, Color.Black, rec, BorderSide.None);
        }

        private void btnSinhPhieuDatHang_Click(object sender, EventArgs e)
        {
            if (gridControlShow.DataSource is DataView)
            {
                DataTable dt = (gridControlShow.DataSource as DataView).ToTable();
                RequestCreateNewPhieuDatHang(dt, (Guid)cmbNhaCungCap.EditValue);
            }
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private DataTable AlphabeticSort(DataTable dtTable, string sortColumn, int sortOrder)
        {
            DataSet dsSorted = new DataSet();
            string columnKey = sortColumn;
            string sortDirection = "";
            string sortFormat = "{0} {1}";
            switch (sortOrder)
            {
                case 0:
                    sortDirection = "ASC";
                    break;
                case 1:
                    sortDirection = "DESC";
                    break;
                default:
                    sortDirection = "ASC";
                    break;
            }

            dtTable.DefaultView.Sort = string.Format(sortFormat, columnKey, sortDirection);

            return dtTable.DefaultView.Table;
        }

        private void chkShowMoreInfo_CheckedChanged(object sender, EventArgs e)
        {
            //colTacGia.Visible = chkShowMoreInfo.Checked;
            //colNXB.Visible = chkShowMoreInfo.Checked;
            //colNCC.Visible = chkShowMoreInfo.Checked;
        }

        private void nmrGioiHanNgay_TextChanged(object sender, EventArgs e)
        {
            if (nmrGioiHanNgay.Text != "")
                _StyleConditionGioiHanSoNgayConHang.Value2 = Convert.ToInt32(nmrGioiHanNgay.Text);
        }
    }
}

